//create new window popup
Ext.define('CDR.widget.GlobalPopup', {
	extend: 'Ext.window.Window',
	alias : 'widget.globalpopup',
	title: 'New Window',
	closable: true,
	closeAction: 'hide',
	width: 375,
	height: 200,
	bodyStyle: 'padding: 5px;',
	targetObject: null,
	type: null,
	checkOn: '',
	url: '',
	addFieldValues : [],
	//set default value
	editData: function(data){
		var name = this.form.down('textfield');
		name.setValue(data.name);
		var description = this.form.down('textareafield');
		description.setValue(data.description);
	},
	initComponent: function() {
       this.callParent();
       var me = this;
	   this.form = Ext.createWidget('form',{
			url: this.url,
			bodyStyle: 'padding: 5px;',
			items:[{
				xtype: 'textfield',
				anchor: '98%',
				allowBlank: false,
				validateOnBlur: true,
				fieldLabel: CDR.I18N['profile.provider.form.name'],
				name: 'name',
				listeners:{
					render: function(){
						Ext.createWidget('checknameValidator',{targetObject: this, checkOn: me.checkOn, listenerObject:{target: me, event:'show'}});
					}
				}
			}, {
				xtype: 'textareafield',
				fieldLabel: CDR.I18N['profile.provider.form.description'],
				anchor: '98%',
				name: 'description'
			}],
			buttons: [{
				text: CDR.I18N['button.save'],
				formBind: true, 
				handler: function() {
					var win = this.up('window');
					if(win.addFieldValues.length > 0){
						Ext.each(win.addFieldValues, function(i){
							var hf = this.down('hidden[name=' + i.name +']');
							if(hf) {
								hf.setValue(i.value);
							}
						},this.up('form'));
					}
					var form = this.up('form').getForm();
					if (form.isValid()) {
						form.submit({
							success: function(form, action) {
							   Ext.Msg.alert('Success', action.result.msg);
							   win.hide();
							   form.reset();
							   if(win.targetObject && win.targetObject.submitOk) {
									win.targetObject.submitOk(action.result, win.type);
							   }
							},
							failure: function(form, action) {
								Ext.Msg.alert('Failed', action.result.msg);
							}
						});
					}
				}
			},{
				text: CDR.I18N['button.cancel'],
				handler: function() {
					var win = this.up('window');
					win.hide();
				}
				
			}]
		});
		var addFields = this.initialConfig.addFields;
		if(addFields){
			Ext.each(addFields, function (item){
				this.add(item);
			}, this.form);
		}
		this.add(this.form);
    }
});

Ext.define('CDR.widget.ServiceProvider', {
	extend: 'Ext.Panel',
	alias : 'widget.serviceprovider',
	title: CDR.I18N['service-provider.title'],
	selectedProviderId : 0,
	selectedProvider : null,
	trunk : null,
	profileCenter : null,
	initComponent: function() {
		var me = this;
		me.callParent();
		me.win = Ext.createWidget('globalpopup', {
			title:'New Service Provider',url:'create-service-provider', checkOn:'SERVICE_PROVIDER' ,targetObject: me, addFields: [{xtype:'hidden', name:'serviceProviderId'}]});
		me.trunk = Ext.createWidget('trunk',{serviceProvider:me});
		//ajax to load items
		Ext.Ajax.request({
			async: false,
			url: 'list-service-provider',
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				Ext.each(obj.results, function(item){
					this.addItem(item.name, item.description, item.id);
				}, me);
			},
			failure: function(response, opts) {
				console.log('server-side failure with status code ' + response.status);
			}
		});
	},
	layout:'anchor',
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: CDR.I18N['service-provider.new'],
			iconCls: 'icon-add',
			handler: function(){
				var me = this.up('panel');
				me.win.setTitle(CDR.I18N['service-provider.new']);
				me.win.type = CDR.Constant.WINDOW_NEW_MODE;
				me.win.form.getForm().reset();
				me.win.show();
			}
		},'-', {
			text: CDR.I18N['service-provider.edit'],
			iconCls: 'icon-edit',
			handler: function(){
				var me = this.up('panel');
				if(me.selectedProviderId == 0){
					Ext.Msg.alert('Failed', "Please seletect a service provider");
					return;
				}
				me.win.setTitle(CDR.I18N['service-provider.edit']);
				me.win.type = CDR.Constant.WINDOW_EDIT_MODE;
				me.win.form.getForm().reset();
				//get pbx and popular data form
				Ext.Ajax.request({
					method: 'GET',
					url:'pbx-service-provider-info',
					params:{'pbxServiceProviderId': me.selectedProviderId},
					success: function(response, opts){
						var obj = Ext.decode(response.responseText);
						me.win.addFieldValues = [{name: 'serviceProviderId', value: me.selectedProviderId}];
						me.win.editData(obj);
						me.win.show();
					}
				});
				me.win.show();
			}
		}]
	}], 
	addItem: function(name, description, id){
		var me = this;
		var com = Ext.createWidget('button',{
			obId: id,
			anchor:'100%',
            text    : name,
            id: 'button-serviceprovider-' + id,
			scale: 'large',
			margin: '0 0 10px 0',
			enableToggle: true,
			toggleGroup:'serviceprovider_bnt',
			handler: function(){
				me.selectedProviderId = this.obId;
				me.selectedProvider = this;
				//get list
				if (me.trunk) {
					var store = me.trunk.view.store;
					store.setProxy({
					  type: 'ajax',
					  url : 'list-trunk-view?serviceProviderId=' + me.selectedProviderId,
					  reader: {
						  type: 'json',
						  root: 'results'
					  }
					});
					store.load();
				}
			}, tooltip: description
		});
		me.add(com);
	},
	submitOk: function(data, type) {
		if (type === CDR.Constant.WINDOW_EDIT_MODE) {
			this.selectedProvider.setText(data.name);
			this.selectedProvider.setTooltip(data.description);
		} else if(type === CDR.Constant.WINDOW_NEW_MODE){
			this.addItem(data.name, data.description, data.id);
		}
	},
	listeners: {
		expand : function(){
			this.profileCenter.removeAll(false);
			this.profileCenter.add(this.trunk);
		}
	}
});

//create trunk view
Ext.define('CDR.widget.TrunkView', {
  extend: 'Ext.view.View',
  alias : 'widget.trunkview',
  targetObject: null,
  tpl: [
      '<tpl for=".">',
          '<div class="thumb-wrap">',
              '<div class="thumb">',
                  (!Ext.isIE6? '<img src="resources/app/images/{thumb}" />' : 
                  '<div style="width:76px;height:76px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'resources/app/images/{thumb}\')"></div>'),
              '</div>',
              '<span>{name}</span>',
          '</div>',
      '</tpl>'
  ],
  
  itemSelector: 'div.thumb-wrap',
  multiSelect: true,
  singleSelect: false,
  cls: 'x-image-view',
  autoScroll: true,
  initComponent: function() {
      this.store = Ext.create('Ext.data.Store', {
          fields: ['name', 'thumb', 'obId']
      });
      this.callParent();
  },
  listeners: {
	itemdblclick: function(me, r){
		if(this.targetObject){
			this.targetObject.proccessDbclick(r);
		}
	}
  }
});

Ext.define('CDR.widget.Trunk', {
	extend: 'Ext.Panel',
	alias : 'widget.trunk',
	serviceProvider: null,
	currentPbx: null,
	initComponent: function() {
		var me = this;
		me.callParent();
		me.win = Ext.createWidget('globalpopup', {
			title:CDR.I18N['service-provider.trunk.new'],url:'create-trunk',checkOn:'TRUNK', targetObject: me,
			addFields: [{xtype:'hidden', name:'serviceProviderId'}, {
				fieldLabel:'Link to PBX',
				xtype: 'combo',
				mode:  'local',
				triggerAction:  'all',
				allowBlank: false,
				anchor: '98%',
				forceSelection: true,
				editable: false,
				name: 'linkTo',
				displayField: 'name',
				valueField: 'id',
				queryMode: 'local',
				store: Ext.create('Ext.data.Store', {
					fields : ['name', 'id']
				})
			}, {
				fieldLabel:'Link to Config',
				xtype: 'combo',
				mode:  'local',
				triggerAction:  'all',
				allowBlank: false,
				anchor: '98%',
				forceSelection: true,
				editable: false,
				name: 'configId',
				displayField: 'name',
				valueField: 'id',
				queryMode: 'local',
				store: Ext.create('Ext.data.Store', {
					fields : ['name', 'id']
				})
			},{
				xtype: 'textfield',
				anchor: '98%',
				fieldLabel: 'Trunk No',
				name: 'trunkNo'
			},{
				xtype:'hidden',
				name:'trunkId'
			}],
			width: 380,
			height: 260,
		});
		me.view = Ext.createWidget('trunkview',{region:'center', targetObject:me});
		me.add(me.view);
	},
	layout:'border',
	bodyStyle:'background-color: white;',
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: CDR.I18N['service-provider.trunk.new'],
			iconCls: 'icon-add',
			handler: function(){
				var me =  this.up('panel');
				if(me.serviceProvider.selectedProviderId == 0){
					Ext.Msg.alert('Failed', "Please seletect a service provider");
					return;
				}
				me.win.type = CDR.Constant.WINDOW_NEW_MODE;
				me.win.form.getForm().reset();
				//set add filed value
				me.win.addFieldValues = [{name: 'serviceProviderId', value: me.serviceProvider.selectedProviderId}];
				//should be load list of pbx
				Ext.Ajax.request({
					scope: this,
					async: false,
					url: 'list-all-pbx',
					success: function(response, opts) {
						var obj = Ext.decode(response.responseText);
						var combo = me.win.form.down('combo[name=linkTo]');
						if(combo){
							combo.store.loadData(obj.results);
						}
					}
				});
				//load all config 
				Ext.Ajax.request({
					url: 'listTariffs',
					success: function(response){
						var data = Ext.decode(response.responseText);
						var rs = [];
						if(data) {
							Ext.iterate(data, function(r){
								rs.push({
									id: r.id,
									name: r.text
								});
							});
							var combo = me.win.form.down('combo[name=configId]');
							if(combo){
								combo.store.loadData(rs);
							}
						}
					}
				});
				me.win.show();
			}
		}, 
		'-' ,
		{
			fieldLabel: CDR.I18N['label.search'],
			labelWidth: 45,
			xtype: 'textfield',
			listeners: {
				'change': function(me, newVal, oldVal){
					var me =  this.up('panel');
					me.view.store.clearFilter();
					me.view.store.filter(new Ext.util.Filter({
							filterFn: function(item) {
								var searchtest,namematch;
								var escapere = Ext.String.escapeRegex;
								searchtest = new RegExp(escapere(newVal), 'i');
								namematch = searchtest.test(item.data.name);
								return namematch;
							}
						})
					);
				}
			}
		}]
	}],
	submitOk: function(data, type) {
		if(type === CDR.Constant.WINDOW_NEW_MODE){
			this.view.store.add({name: data.name, obId: data.obId, thumb: data.thumb});
		} else if(type === CDR.Constant.WINDOW_EDIT_MODE){
			this.currentPbx.set('name', data.name);
		}
	},
	proccessDbclick: function(r){
		this.currentPbx = r;
		var id = r.data.obId;
		this.win.form.getForm().reset();
		this.win.type = CDR.Constant.WINDOW_EDIT_MODE;
		Ext.Ajax.request({
			scope: this,
			async: false,
			url: 'trunk-info?trunkId=' + id,
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				this.win.addFieldValues = [{name: 'serviceProviderId', value: obj.result.serviceProviderId},{name: 'trunkId', value: obj.result.obId}];
				this.win.form.down('textfield[name=trunkNo]').setValue(obj.result.trunkNo);
				var combo = this.win.form.down('combo[name=linkTo]');
				var comboConfig = this.win.form.down('combo[name=configId]');
				if(combo){
					combo.store.loadData(obj.result.linkTo);
					if(obj.result.pbxId){
						combo.setValue(obj.result.pbxId);
					}
				}
				if(comboConfig){
					comboConfig.store.loadData(obj.result.configs);
					if(obj.result.configId){
						comboConfig.setValue(obj.result.configId);
					}
				}
				this.win.editData(obj.result);
				this.win.show();
			}
		});
	}
});
